﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using Common.Util;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using Dewin.BO.AgentMember;
using Dewin.BO.Model;
using Dewin.BO.Util;
using Log.Controller;
using Tabber.Model;
using Tabber.Util;

namespace Tabber.Forms
{
    public partial class AgentEdit : DevExpress.XtraEditors.XtraForm
    {
        #region Variables
        /// <summary>
        /// Bien de luu id cua agent
        /// </summary>
        public string AgentId = string.Empty;

        /// <summary>
        /// Bien luu thong tin doi tuong agent lay tu file
        /// </summary>
        private Agent _agent = null;
        #endregion

        #region Initializing
        public AgentEdit()
        {
            InitializeComponent();
            SetText();
        }

        /// <summary>
        /// Set text base on language
        /// </summary>
        private void SetText()
        {
            try
            {
                Text = TabberCommon.GetString("Agent");
                layoutControlItem1.Text = TabberCommon.GetString("Id");
                layoutControlItem3.Text = TabberCommon.GetString("Username");
                layoutControlItem4.Text = TabberCommon.GetString("Password");
                layoutControlItem6.Text = TabberCommon.GetString("AgentType");
                layoutControlItem5.Text = TabberCommon.GetString("Address");
                layoutControlItem7.Text = TabberCommon.GetString("Member");
                layoutControlItem9.Text = TabberCommon.GetString("DelayTime");
                btnSave.Text = TabberCommon.GetString("Save");
                btnSaveCont.Text = TabberCommon.GetString("SaveCont");
                btnClose.Text = TabberCommon.GetString("Close");
            }
            catch (Exception ex)
            {
                LogController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Network.GetLocalIp());
            }
        }

        /// <summary>
        /// Su kien load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AgentEdit_Load(object sender, EventArgs e)
        {
            try
            {
                LoadType();

                _agent = Agent.GetAccount(AgentId);
                if (_agent != null)
                {
                    // Get account's info then fill in the textboxes
                    txtId.Text = _agent.Id;
                    txtUsername.Text = _agent.Username;
                    cboType.Text = _agent.Type;

                    LoadDomain();

                    cboDomain.Text = _agent.Address;
                    txtPassword.Text = DeEncrypt.Decode(_agent.Password);

                    // Because using only member agent and agent, so this fields will be removed on next phase
                    var member = _agent.Members != null && _agent.Members.Any() ? _agent.Members.First() : null;
                    txtMember.Text = member != null ? member.Username : string.Empty;
                    spinDelayTime.EditValue = member != null && member.Settings.Any() ? member.Settings.First().DelayTime / 1000 : 0;
                }

                // Set focus
                txtUsername.Focus();
            }
            catch (Exception ex)
            {
                LogController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Network.GetLocalIp());
            }
        }

        /// <summary>
        /// Su kien form dang dong
        /// Kiem tra xem co thay doi gi so voi ban goc ko
        /// Neu co thi thong bao hoi co save khong
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AgentEdit_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Neu form ko valid thi dong, khong can hoi
            if (!ValidateFields()) return;

            // Neu form valid thi so sanh xem cac gia tri co thay doi gi khong
            // Neu co thi hoi
            if (_agent == null || string.IsNullOrEmpty(AgentId) || _agent.Id != AgentId
                || _agent.Username != txtUsername.Text || _agent.Address != cboDomain.Text || _agent.Password != DeEncrypt.Encode(txtPassword.Text))
            {
                // Hien thi dialog confirm
                var confirm = MessageBox.Show("Bạn có muốn lưu thông tin Agent trước khi đóng không?",
                                              "Thông báo", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
                                              MessageBoxDefaultButton.Button1);
                if (confirm == DialogResult.Yes)
                {
                    SaveAgent();
                }
                else if (confirm == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Load danh sach Address
        /// </summary>
        private void LoadDomain()
        {
            try
            {
                // Lay gia tri truoc khi load
                var value = cboDomain.Text;

                // Lay danh sach domain theo Type, Side
                var list = Domain.GetDomains(cboType.Text, Side.Agent);

                // Xoa list cu
                cboDomain.Properties.Items.Clear();
                foreach (var domain in list)
                {
                    cboDomain.Properties.Items.Add(domain.Address);
                }

                // Set lai thuoc tinh
                cboDomain.Text = value;
            }
            catch (Exception ex)
            {
                LogController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Network.GetLocalIp());
            }
        }

        /// <summary>
        /// Load danh sach Address
        /// </summary>
        private void LoadType()
        {
            try
            {
                // Lay gia tri truoc khi load
                cboType.Properties.DataSource = Provider.GetProvider();

                // Set mac dinh la SBO
                cboType.Text = Provider.Sbo;
            }
            catch (Exception ex)
            {
                LogController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Network.GetLocalIp());
            }
        }

        /// <summary>
        /// Su kien value cua Type change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboType_EditValueChanged(object sender, EventArgs e)
        {
            LoadDomain();
        }
        #endregion

        #region Luu agent
        /// <summary>
        /// Su kien nhan nut luu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveAgent();
            Close();
        }

        /// <summary>
        /// Su kien nhan luu va mo form quan ly member
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveCont_Click(object sender, EventArgs e)
        {
            SaveAgent();
        }

        /// <summary>
        /// Ham so sanh va luu thong tin agent
        /// </summary>
        private void SaveAgent()
        {
            try
            {
                // Validate cac gia tri
                if (!ValidateFields()) return;

                if (_agent == null)
                {
                    // Neu agent chua co thi tao moi
                    _agent = new Agent
                    {
                        Id = string.Empty,
                        Username = txtUsername.Text,
                        Type = cboType.Text,
                        Address = cboDomain.Text,
                        Password = DeEncrypt.Encode(txtPassword.Text),

                        // Hien tai chi lam 1 member thoi, se xoa cai nay khi lam multi member
                        Members = new List<Dewin.BO.AgentMember.AgentMember>
                            {
                                new Dewin.BO.AgentMember.AgentMember
                                    {
                                        Username = txtMember.Text, 
                                        Settings = new List<MemberAgentSetting>
                                            {
                                                new MemberAgentSetting { DelayTime = (int)spinDelayTime.EditValue }
                                            }
                                    }
                            }
                    };
                }
                else
                {
                    // Set lai gia tri cho doi tuong _agent
                    _agent.Username = txtUsername.Text;
                    _agent.Address = cboDomain.Text;
                    _agent.Type = cboType.Text;
                    _agent.Password = DeEncrypt.Encode(txtPassword.Text);

                    // Hien tai chi lam 1 member thoi, se xoa cai nay khi lam multi member
                    _agent.Members = new List<Dewin.BO.AgentMember.AgentMember>
                            {
                                new Dewin.BO.AgentMember.AgentMember
                                    {
                                        Username = txtMember.Text, 
                                        Settings = new List<MemberAgentSetting>
                                            {
                                                new MemberAgentSetting { DelayTime = Convert.ToInt32(spinDelayTime.EditValue) * 1000 }
                                            }
                                    }
                            };
                }

                if (Agent.Save(_agent))
                {
                    // Neu luu thanh cong thi set lai agent id
                    AgentId = _agent.Id;
                }
            }
            catch (Exception ex)
            {
                LogController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Network.GetLocalIp());
            }
        }
        #endregion

        #region Validating
        /// <summary>
        /// Su kien validate Username
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtUsername_Validating(object sender, CancelEventArgs e)
        {
            ValidateEmptyStringRule(sender as BaseEdit);
        }

        /// <summary>
        /// Su kien validate Password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPassword_Validating(object sender, CancelEventArgs e)
        {
            ValidateEmptyStringRule(sender as BaseEdit);
        }

        /// <summary>
        /// Su kien validate Address
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboDomain_Validating(object sender, CancelEventArgs e)
        {
            ValidateEmptyStringRule(sender as BaseEdit);
        }

        /// <summary>
        /// Su kien validate member
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtMember_Validating(object sender, CancelEventArgs e)
        {
            ValidateEmptyStringRule(sender as BaseEdit);
        }

        /// <summary>
        /// Ham kiem tra rong
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        private bool ValidateEmptyStringRule(BaseEdit control)
        {
            control.Text = control.Text.Trim();
            if (control.Text == null || control.Text.Trim().Length == 0)
            {
                dxErrorProvider1.SetError(control, "This field can't be empty", ErrorType.Critical);
                return false;
            }

            dxErrorProvider1.SetError(control, "");
            return true;
        }

        /// <summary>
        /// Ham validate cac control truoc khi save
        /// </summary>
        /// <returns></returns>
        private bool ValidateFields()
        {
            return ValidateEmptyStringRule(txtUsername) && ValidateEmptyStringRule(txtPassword)
                    && ValidateEmptyStringRule(cboDomain) && ValidateEmptyStringRule(txtMember);
        }
        #endregion

        #region Key
        /// <summary>
        /// Su kien key down
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AgentEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.S && e.Control)
            {
                // Bat phim Ctrl+S de save va continue
                btnSaveCont_Click(btnSaveCont, null);
            }
        }
        #endregion

    }
}